<template>
  <a-popover trigger="click" placement="bottom" v-model:open="visible">
    <slot>
      <a-tooltip title="备忘录">
        <FileOutlined />
      </a-tooltip>
    </slot>
    <template #content>
      <a-list title="系统备忘录" bordered class="mt-8" :data-source="dictData" size="small">
        <template #renderItem="{ item }">
          <a-list-item @dblclick="confirm(item.value)" class="hover-item">
            <a-list-item-meta :title="item.title" :description="item.value"></a-list-item-meta>
            <template #actions>
              <a-button type="text" @click="confirm(item.value)">使用</a-button>
            </template>
          </a-list-item>
        </template>
        <template #footer>
          <a-pagination
            :page-size="query.pageSize"
            :current="query.pageNum"
            :total="query.total"
            @change="onPageChange"
          ></a-pagination>
        </template>
      </a-list>
    </template>
  </a-popover>
</template>

<script setup lang="ts">
import type { IQuery } from '@/api/config/types';
import { createMemo, fetchMemoList } from '@/api/modules/ax/memo/memo';
import type { AxMemo } from '@/api/modules/ax/memo/types';
import { response } from '@/utils/table/table';

import { FileOutlined } from '@ant-design/icons-vue';

type Value = string | number | undefined;

const visible = ref(false);
const dictData = ref<AxMemo[]>([]);
const newMemo = ref<string>('');
const emit = defineEmits(['update:modelValue']);

const loading = ref(true);

const query = ref<IQuery>({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  type: '1',
});

defineProps<{
  modelValue: Value;
}>();
const onPageChange = (page: number, pageSize: number) => {
  query.value.pageNum = page;
  query.value.pageSize = pageSize;
  getList();
};

const confirm = (value: Value) => {
  emit('update:modelValue', value);
  visible.value = false;
};

const getList = async () => {
  loading.value = true;
  const { data } = await fetchMemoList(query.value);
  dictData.value = data.rows;
  query.value.total = data.total;
  loading.value = false;
};

onMounted(() => {
  getList();
});

const create = async () => {
  if (newMemo.value) {
    await response(createMemo, {
      title: newMemo.value.slice(0, 10),
      type: query.value.type,
      value: newMemo.value,
    });
    getList();
  }
};
</script>

<style lang="scss" scoped>
.system-memo {
  width: 400px;
}

.hover-item {
  &:hover {
    outline: 1px solid var(--primary);
  }
}
</style>
